import { useEffect, useState, useCallback, useRef } from 'react';
import { List, Checkbox } from 'antd-mobile';
import service from './service';
import SimpleListView from '@inbiz/basic/SimpleListView';
import styles from './index.less';
import SelectBar from './SelectBar';
import { getLowercase } from './utils/index';

export default function UserGroupTab(props: any) {
  const listRef = useRef<any>();
  const [data, _data] = useState<any[]>([]);

  const { selected, selectedId, allSelected, multiple, onOk, onCancel, setSelected, tabKey } =
    props;

  const onRefresh = useCallback((params: any) => {
    service.getUserGroupList({}).then((res) => {
      _data(getLowercase(res, tabKey) || []);
      // 每次刷新滚动到顶部
      listRef.current?.scroll(0, 0);
    });
  }, []);

  const onRowSelectChange = useCallback(
    (row: any) => {
      return (checked: boolean) => {
        let index = selectedId.indexOf(row.key);
        if (checked) {
          if (index == -1) {
            let newSelected = [...selected, row];
            setSelected(newSelected);
          }
        } else {
          if (index > -1) {
            let newSelected = [...selected];
            newSelected.splice(index, 1);
            setSelected(newSelected);
          }
        }
        props.updateSelected && props.updateSelected(checked, row);
      };
    },
    [selectedId, selected],
  );

  useEffect(() => {
    service.getUserGroupList({}).then((res) => {
      _data(getLowercase(res, tabKey) || []);
    });
  }, []);

  return (
    <div className={styles.userGroupTab}>
      <SimpleListView
        ref={listRef}
        onRefresh={onRefresh}
        renderRow={(row: any, index: number) => {
          return (
            <List.Item
              key={index}
              extra={
                <Checkbox
                  checked={selectedId.includes(row.key)}
                  onChange={onRowSelectChange(row)}
                />
              }
            >
              {row.name}
            </List.Item>
          );
        }}
        dataSource={data}
      />
      <SelectBar
        filterKey={tabKey}
        data={data}
        selectedId={selectedId}
        selected={selected}
        allSelected={allSelected}
        multiple={multiple}
        setSelected={setSelected}
        onOk={onOk}
        onCancel={onCancel}
      />
    </div>
  );
}
